package com.cloud.common.context;

import com.cloud.common.util.UUIDUtils;
import org.slf4j.MDC;
import org.springframework.util.StringUtils;

/**
 * 跟踪上下文
 *
 * @author fengwenjin
 */
public class TraceContext {

    public static final String TRACE_ID = "traceId";

    public static String create(String userId) {
        userId = userId == null ? "" : "@" + userId;
        return Math.abs(UUIDUtils.get().hashCode()) + userId;
    }

    public static void set(String traceId) {
        traceId = StringUtils.isEmpty(traceId) ? create(null) : traceId;
        MDC.put(TRACE_ID, traceId);
    }

    public static String get() {
        return MDC.get(TRACE_ID);
    }

    public static void remove() {
        MDC.clear();
    }

}
